package com.itjiange.controller;

import com.itjiange.pojo.User;
import com.itjiange.service.UserService;
import com.itjiange.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 查询所有用户
 *
 * @author ItJiange
 * @date 2023/10/17
 */
@WebServlet("/user/selectAll")
public class UserSelectAllController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 0. 设置响应信息
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 1. 获取写入流
        PrintWriter writer = resp.getWriter();
        // 2. 获取查询结果
        List<User> userList = userService.userAll();
        // 编写html页面
        String html = "<style>\n" +
                "        table, tr, td {\n" +
                "            border: 1px solid black;\n" +
                "        }\n" +
                "    </style>\n" +
                "    <table>\n" +
                "        <tr>\n" +
                "            <td>id</td>\n" +
                "            <td>用户名</td>\n" +
                "            <td>邮箱</td>\n" +
                "            <td>爱好</td>\n" +
                "            <td>注册时间</td>\n" +
                "            <td>修改时间</td>\n" +
                "        </tr>\n";
        for (User user : userList) {
            html += "        <tr>\n" +
                    "            <td>" + user.getId() + "</td>\n" +
                    "            <td>" + user.getUsername() + "</td>\n" +
                    "            <td>" + user.getEmailaddress() + "</td>\n" +
                    "            <td>" + user.getHobby() + "</td>\n" +
                    "            <td>" + user.getCreatetime() + "</td>\n" +
                    "            <td>" + user.getUpdatetime() + "</td>\n" +
                    "        </tr>\n";
        }
        html += "</table>";
        writer.write(html);
        // 关闭流
        writer.close();
    }
}
